﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Web.Mvc;
using System.ComponentModel;
using Lilium.Web.Mvc.Metadata;

namespace Lilium.Web.Mvc
{
	public static class RouteValueDictionaryExtensions
	{
		public static void AddEntityKey<TEntity>(this RouteValueDictionary routeValues, TEntity entity, EntityActionDescription actionDescription)
		{
			if (routeValues == null) throw new ArgumentNullException("routeValues");
			if (entity == null) throw new ArgumentNullException("entity");
			if (actionDescription == null) throw new ArgumentNullException("actionDescription");

			var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => entity, typeof(TEntity));
			var entityMetadata = modelMetadata.FindExtension<EntityMetadataExtension>(true);
			var entityProperties = TypeDescriptor.GetProperties(typeof(TEntity));

			foreach (var keyName in entityMetadata.EntityKey.KeyNames)
			{
				if (actionDescription.FindParameter(keyName) == null)
					throw new InvalidOperationException(string.Format(
						"Action {0} does not except parameter {1}", actionDescription.ActionName, keyName));
				routeValues[keyName] = entityProperties[keyName].GetValue(entity);
			}
		}

		public static RouteValueDictionary GetRouteValues(IDictionary<string, object> routeValues)
		{
			if (routeValues == null)
			{
				return new RouteValueDictionary();
			}
			return new RouteValueDictionary(routeValues);
		}

		[Obsolete("Найти где это используется, скорее всего этот код не нужен.")]
		public static RouteValueDictionary MergeRouteValues(string actionName, string controllerName, RouteValueDictionary implicitRouteValues, IDictionary<string, object> routeValues, bool includeImplicitMvcValues)
		{
			RouteValueDictionary dictionary = new RouteValueDictionary();
			if (includeImplicitMvcValues)
			{
				object obj2;
				if ((implicitRouteValues != null) && implicitRouteValues.TryGetValue("action", out obj2))
				{
					dictionary["action"] = obj2;
				}
				if ((implicitRouteValues != null) && implicitRouteValues.TryGetValue("controller", out obj2))
				{
					dictionary["controller"] = obj2;
				}
			}
			if (routeValues != null)
			{
				foreach (KeyValuePair<string, object> pair in GetRouteValues(routeValues))
				{
					dictionary[pair.Key] = pair.Value;
				}
			}
			if (actionName != null)
			{
				dictionary["action"] = actionName;
			}
			if (controllerName != null)
			{
				dictionary["controller"] = controllerName;
			}
			return dictionary;
		}

	}
}
